<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 2015/7/1
 * Time: 17:25
 */
namespace Institution\Controller;
use Think\Controller;
use Think\Model\ViewModel;
use Think\Think;
use Api\Department\DepartmentApi;
use User\Api\UserApi;
use Admin\Model\AuthRuleModel;
use Admin\Model\AuthGroupModel;
class UnitController extends  AdminController{
    public function index(){
        $unit = M('Department')->select();
        $this->assign('unit', $unit);
        $this->display();
    }
    /*
     * 审核机构
     */
    public function doAuditUnit(){
        if(IS_AJAX){
            $id = I('get.id');
            if(empty($id)){
                $return['status'] = 0;
                $retrun['data'] = '';
                echo json_encode($return);exit;
            }
            $unit = new DepartmentApi();
            //取得机构用户的
            $info = $unit->getInfo($id);
            //创建机构用户的账号
            if($uid=$this->_addUser($info)){
                //审核通过用户
                $result = $unit->audit($id);
                //添加用户权限
                $auth = D('AuthGroupAccess')->addGroup($uid,"1");
                if(!$auth){
                    $this->error('对不起，添加用户权限失败');exit;
                }
                if(!$result){
                    $this->error("审核用户没有通过");
                }
                $this->success('审核用户通过');
            }else{
                $this->error('创建用户失败，账户名称可能已经被注册或者邮箱已经创建过账户');
            }
        }
    }

    /*
     * 机构编辑
     */
    public function edit(){
        if(IS_POST){
            $data = I('post.');
            $Department = new DepartmentApi();
            $departmentId = $Department->update($data);
            if($departmentId>0){
                $this->success('保存成功',U('Unit/info'));
            }else{
                $this->error($this->showRegError($departmentId));
            }
        }else{
            $id = I('get.id');
            $Department = new DepartmentApi();
            $info = $Department->info($id);
            $this->getCategory();
            $this->assign('info', $info);
            $this->assign('meta_title', '机构管理');
            $this->display();
        }
    }
    /**
     * 机构设置
     */
    public function set(){
        if(IS_POST){
            $data = I('post.');
            $depart_id = I('depart_id');
            $Department = M('Unit');
            $departmentId = $Department->where('depart_id='.$depart_id)->save($data);
            if($departmentId>0){
                $this->success('保存成功',U('Unit/set'));
            }else{
                $this->error($this->showRegError($departmentId));
            }
        }else{
            $AgencyId = $this->getDepartment();
            $info = M('Unit')->where('depart_id='.$AgencyId)->find();
            $this->assign('info', $info);
            $this->assign('AgencyId', $AgencyId);
            $this->assign('meta_title', '查新机构设置');
            $this->display();
        }
    }
    /*
     * 添加机构
     */
    public function add(){
        if(IS_AJAX){
            $data = I('post.');
            $Department = new DepartmentApi();
            $departmentId = $Department->register($data);
            if($data['typeid'] == 2 && $data['unit'] == '')
            {
                $this->error('请填写挂靠单位');
            }
            $data['id'] = $departmentId;
            if(0<$departmentId){
                $this->success('添加成功',U('Unit/index'));
            }else{
                $this->error($this->showRegError($departmentId));
            }
        }else{
            $this->display('edit');
        }
        $this->assign('meta_title', '机构管理');
    }
    /*
     * 机构信息
     */
    public function info(){
        if(UID){
            $AgencyId = $this->getDepartment();
            $Department = new DepartmentApi();
            $info = $Department->info($AgencyId);
            $this->getCategory();
            $this->assign('info', $info);
            $this->assign('meta_title', '机构管理');
            $this->display();
        }
    }
    /*
     * 机构人员管理
     */
    public function user(){
        $roleId = I('get.roleId');
        if($roleId && isset($roleId)){
            $map1['typeid'] = $roleId;
        }
        $departmentId = M('User')->find(UID);
        $map['department'] = $departmentId['department'];
        $map1['department'] = $departmentId['department'];
        $map1['_string'] = ' typeid != 1';      //去除机构用户
        $map['id'] = array('neq',UID);
//        $User = M('User');
        $list = $this->lists(M('User'),$map1);
        $map['module']='Institution';
        $map['status']=1;
        $map['sid']=$departmentId['department'];
        $group=M('auth_group')->where($map)->select();
        $this->assign('department', $departmentId['department']);
        $this->assign('_list', $list);
        $this->assign('meta_title', '人员管理');
        $this->assign('group', $group);//查询该登陆用户所属机构的用户组
        $this->assign('search_roleid', $roleId);//返回查询的roleid
        if(isset($_GET['p'])){
            $num = ($_GET['p']-1)*10;
            $this->assign('num', $num);
        }
        $this->display();
    }
    /*
     * 添加机构时添加的用户
     */
    private function _addUser($department){
        $user = new UserApi();
        $passoword = "123456";
        $uid = $user->register($department['username'],$passoword,$department['email']);
        $data['department'] = $department['id'];
        $user->updateInfo($uid,$data);
        $data1 = array(
            'id'=>$department['id'],
            'uid'=>$uid
        );
        $res = D('Department')->data($data1)->save();
        if($res){
            return $uid;
        }else{
            return -1;
        }
    }

    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '用户名长度必须在16个字符以内！'; break;
            case -2:  $error = '用户名被禁止注册！'; break;
            case -3:  $error = '用户名被占用！'; break;
            case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机格式不正确！'; break;
            case -10: $error = '手机被禁止注册！'; break;
            case -11: $error = '手机号被占用！'; break;
            case -12: $error = '机构名称长度必须在250个字符以内！'; break;
            case -13: $error = '通讯地址长度必须在250个字符以内！'; break;
            case -14: $error = '请填写挂靠单位'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }
    
    /*************cp*****************/
    /*
     * 机构流程设置
    */
    public function process(){
        $depart_id=M('department')->where("uid=".UID)->getField('id');
        if(!$depart_id)
        {
            $this->error('必须是机构管理员才能操作');
        }
        $map['department_id'] = $depart_id;
    	$list=M('CxProcess')->where("process_id != '' ")->where($map)->select();
    	$this->assign('list',$list);
        $this->assign('meta_title', '流程管理');
    	$this->display();
    }
    
    //
    public function processEdit(){
    	if(IS_POST){
    		$data	=	I('post.');
    		$id		=	I('id');
    		
    		$user_list_arr=M('CxProcess')->where('id	= '.$id)->field('check_user,show_user_id')->select();

    		if($data[task_menu]){$data[task_menu]=implode(',',$data[task_menu]);}
    		if($data[check_user]){
    			$data[check_user]=$this->get_new_userid($user_list_arr[0]['check_user'],$data[check_user]);
    		}else{
    			$data[check_user]=$this->get_new_userid($user_list_arr[0]['check_user'],array());
    		}
    		if($data[show_user_id]){
    			$data[show_user_id]=$this->get_new_userid($user_list_arr[0]['show_user_id'],$data[show_user_id]);
    		}else{
    			$data[show_user_id]=$this->get_new_userid($user_list_arr[0]['show_user_id'],array());
    		}
    		$process = M('CxProcess')->data($data)->save();
    		if($process){
    			$this->success('保存成功',U('process'));
    		}else{
    			$this->error('保存失败');
    		}
    	}else{
    		$id			=	I('pid');
            if($id)    //修改
            {
                $map['id']	=	$id;
                $process_one=M('CxProcess')->where("id = $id")->select();
				// echo json_encode($process_one);exit;
                $this->assign('process_one',$process_one);

            }
            $user_list = $this->get_jg_user();//获取机构馆员
            $this->assign('user_list', $user_list);

            $fun_id=$this->get_menu_conf();
            $this->assign('meta_title', '流程管理');
            $this->assign('fun_id', $fun_id);
    		$this->display();
    	}
    }
    
    //获取机构馆员
    private function get_jg_user($tags=''){
    	$depart_id=M('department')->where("uid=".UID)->getField('id');
        if(!$depart_id)
        {
            return false;
        }
        $user = M('user');
    	if($tags == ''){
            $user_list=$user->where("department=".$depart_id)->field('id,username')->select();
    	}else{
            $user_list=$user->where("department=".$depart_id)->field('id')->select();
    	}
    	return $user_list;
    }
    //获取机构下的流程
    private function get_process(){
    	$process_list=M('CxProcess')->where("process_id != '' AND tag=1 AND department_id=".DEPARTMENT_ID)->field('process_id,title')->select();
    	//     	print_r($process_list);exit;
    	return $process_list;
    }
    
    //获取机构下可执行功能
        private function get_menu_conf(){
    	$fun_id=M('MenuConf')->where('department_id='.DEPARTMENT_ID)->field('id,title')->select();
    	return $fun_id;
    }
     
    //功能键页面
    public function funmenu(){
        //判断机构下所有人员是否有审核员
        $map['department'] = DEPARTMENT_ID;
        $map['typeid']     = array('eq',12);
        $userType = M('User')->where($map)->select();
        if(!empty($userType)){
            $list=M('MenuConf')->where(array('is_true'=>'1','department_id'=>DEPARTMENT_ID))->order('id ASC')->select();
        }else{
            $where['department_id'] = DEPARTMENT_ID;
            //$where['title']         = array('neq','分配审核人员');
            $where['is_true']       =array('eq',1);
            $list=M('MenuConf')->where($where)->order('id ASC')->select();
        }
    	$this->assign('list',$list);
        $this->assign('meta_title', '功能键管理');
    	$this->display();
    }
    
    //功能键编辑+添加功能
    public function funmenuEdit(){
    	if(IS_POST){
    		$data	=	I('post.');
    		$id		=	I('id');
            if($id){
                $user_list_arr=M('MenuConf')->where('id	= '.$id)->field('check_user')->find();
                if($data[check_user]){
                    $data[check_user]=$this->get_new_userid($user_list_arr['check_user'],$data[check_user]);
                }else{
                    $data[check_user]=$this->get_new_userid($user_list_arr['check_user'],array());
                }
                $process = M('MenuConf')->save($data);
                //     		echo M('MenuConf')->getLastSql();exit;
                if($process){
                    $this->success('操作成功',U('funmenu'));
                }else{
                    $this->error('保存失败');
                }
            }else{
                $data['is_true']    =   1;
                $data['department_id'] = DEPARTMENT_ID;
                $process = M('MenuConf')->add($data);
                if($process){
                    $this->success('操作成功',U('funmenu'));
                }else{
                    $this->error('保存失败');
                }
            }

    	}else{
    		$id			=	intval(I('pid'));
            if($id){
                $map['id']	=	$id;
                $funmenu_one=M('MenuConf')->where("id = $id")->find();
            }
    		$this->assign('funmenu_one',$funmenu_one);
    		$user_list=$this->get_jg_user();
            if(!$user_list)
            {
                $this->error('必须是机构管理员才能操作此功能');
            }
            $this->assign('meta_title', '功能键管理');
            $this->assign('user_list', $user_list);
            $process_list=$this->get_process();
    		$this->assign('process_list', $process_list);
    		$this->display();
    	}
    }
    //功能键添加页面跳转
    public function funmenuAdd(){
        $this->display('Unit/funmenuEdit');
    }
    //功能键删除【更改状态不显示在页面上】显示状态：1；不显示为：0
    public function funmenudel(){
        $id			=	I('pid');
        $data['is_true']    =   0;
        $data['id']          =  $id;
        $process = M('MenuConf')->data($data)->save();
        if($process){
            $this->success('删除成功',U('funmenu'));
        }else{
            $this->error('删除失败');
        }

    }
    //流程管理更新用户id
    public function get_new_userid($old_ids,$add_ids){
    	$jg_user_arr=$this->get_jg_user('id');
    	$jg_user_arr1=array();
    	foreach ($jg_user_arr as $key => $vlaue){
    		$jg_user_arr1[]=$jg_user_arr[$key]['id'];
    	}

        if($old_ids !=''){
    		$old_ids_arr=explode(',',$old_ids);
    		$same_id_arr=array_intersect($old_ids_arr,$jg_user_arr1);//查找出已有本机构的用户
    		$jigou_ids=array_diff($old_ids_arr,$same_id_arr);//删除本机构用户
    		$new_ids_arr=array_merge($jigou_ids,$add_ids);
    	}else{
    		$new_ids_arr=$add_ids;
    	}
    	return implode(',',array_unique($new_ids_arr));
    }

    //获取所有的查新范围
    private function getCategory(){
        $list = M('SchoolType')->where('status=1')->select();
        $this->assign('category',$list);
    }

    /* 用户组查询显示*/
    public  function  user_group(){
        $map['sid']= M('User')->where("id=".UID)->getField('department');
        $map['module']='Institution';
        $map['status']=1;
        $list=M('auth_group')->where($map)->select();
        $this->assign('list',$list);
        $this->assign('meta_title', '用户组管理');
        $this->display();
    }
    /* 增加、编辑用户组*/
    public  function  user_group_add(){
        $departmentId = M('User')->where("id=".UID)->getField('department');
        $id=intval(I('id'));
        $data = array();
        $data['title'] = I('title');
        $data['description'] =I('description');
        $data['stu_group'] = I('stu_group');
        $data['module']=I('module');
        $data['type']=1;
        $data['is_true']=0;   //机构创建的在admin不显示
        $data['sid']=$departmentId;
        if(strlen($data['title']) > 20)    //2016.6.16 teng \\u4e00-\\u9fa5
        {
            $this->error('用户组名称最多20个字符串长度');
        }
       if($id){
           //2016.7.6  teng 添加判断本机构中的组不能重复
           $result = M('auth_group')->where("id = $id")->find();
           if(!$result)
           {
               $this->error('用户组不存在');
           }
           if(M('auth_group')->where("title = '$data[title]' and sid = $departmentId  and id != $id")->find())  //一个机构中的组名称不能重复
           {
               $this->error('本机构中用户组已存在');
           }
           if(M('auth_group')->where("id = '$id'")->save($data)){
               $this->success('修改成功',U('user_group'));
           }else{
               $this->error('修改失败！');
           }
       }else{
           if(M('auth_group')->where("title = '$data[title]' and sid = $departmentId")->find())  //一个机构中的组名称不能重复
           {
               $this->error('本机构中用户组已存在');
           }
           if(M('auth_group')->where("id = '$id'")->add($data)){
               $this->success('添加成功',U('user_group'));
           }else{
               $this->error('添加失败！');
           }
       }
    }

    /**
     * 删除用户组
     * 2016.7.20 修改
     */
    public function user_group_del(){
        $id=I('id');
        if(M('auth_group')->find(I('id')))
        {
            if(M('auth_group')->where("id = '$id'")->delete()){
                $this->success('删除成功！');
            }else{
                $this->error('删除失败！');
            }
        }
        else
        {
            $this->error('该用户组不存在！');
        }

    }

    //用户组列表查询
    public function  user_list(){
        $roleId = intval(I('roleId'));
        $map['typeid'] = $roleId;
        $type_name=M('auth_group')->where(array('id'=>$roleId))->getField('title');
        if(!$type_name)
        {
            JsLocation('参数错误');
        }
        else
        {
            $map['department'] = DEPARTMENT_ID;
            $map['id'] = array('neq',UID);
            $User = M('User');
            $list = $User->where($map)->select();
            $this->assign('department', DEPARTMENT_ID);
            $this->assign('type_name', $type_name);
            $this->assign('list', $list);
            Cookie('__forward__',$_SERVER['REQUEST_URI']); //保存url
            $this->display();
        }

    }
    /*
   * 用户组用户添加
   */
    public function useradd(){
        $department = M('User')->where('id='.UID)->getField('department');
        if(IS_POST){
            $data = I('post.');
            $User = new UserApi;
            $uid = $User->register($data['username'],'888888',$data['email'] ,$data['tel']);//新增用户初始密码为888888
            if(0 < $uid) {
                $array = array(
                    'department' => $department,
                    'name' => $data['name'],
                    'city' => $data['city'],
                    'address' => $data['address'],
                    'typeid' => $data['typeid'],
                );
                $uid_1 = M('User')->where(array('id'=>$uid))->save($array);
                if ($uid_1) {
                    $u_g['uid'] = $uid;
                    $u_g['group_id'] = $data['typeid'];
                    if (M('auth_group_access')->add($u_g)) {
                        $this->redirect('user_list?roleId=' . $data['typeid']);
                    } else {
                        $this->error('用户没有添加进用户组');
                    }
                } else {
                    $this->error('用户添加失败');
                }
            }else{
                $this->error($this->showRegError($uid));
            }
        }
        $map['module']='Institution';
        $map['status']=1;
        $map['sid']=$department;
        $group=M('auth_group')->where($map)->select();
        $this->assign('group', $group);
        $this->display();
    }
    /*
   * 用户组用户修改
   */
    public function unitEdit(){
        $department = M('User')->where('id='.UID)->getField('department');
        $map['module']='Institution';
        $map['status']=1;
        $map['sid']=$department;
        $group=M('auth_group')->where($map)->select();
        $User = new UserApi();
        if(IS_POST){
            $data = I('post.');
            if($res = $User->updateInfo($data['id'],$data)){
                $this->success('更新用户信息成功',U('user_list?roleId='.$data['typeid']));
            }else{
                $this->error('请修改用户信息');
            }
        }else{
            $id = I('get.id');
            $info = $User->info($id);
            $this->assign('info', $info);
            $this->assign('group', $group);
            $this->display('useradd');
        }
    }
    /*
    * 用户组用户启用和禁用
    */
    public function changeStatus($method,$id){
        $map['id'] = $id;
        switch($method){
            case 'forbidUser':
                $this->forbidUser('User',$map);
                break;
            case 'resumeUser':
                $this->resumeUser('User',$map);
                break;
            default :
                $this->error('非法参数');
        }
    }
    /*
   * 禁用用户
   * $model 模块
   * $map条件
   */
    protected function forbidUser($model, $map){
        $data['status'] = 0;
        $res = M($model)->where($map)->data($data)->save();
        if($res){
            $this->success('状态禁用成功');
        }else{
            $this->error('状态禁用失败');
        }
    }
    /*
        * 启用用户
        */
    protected function resumeUser($model,$map){
        $data['status'] =1;
        $res = M($model)->where($map)->data($data)->save();
        if($res){
            $this->success('启用用户成功');
        }else{
            $this->error('启用用户失败');
        }
    }

    //功能权限设置
    public function access(){
        $id =(int)I('group_id');
        $module = $this->getModuleByGroupID($id);
        $this->updateRules($module);
        $auth_group = M('AuthGroup')->where(array('status' => array('egt', '0'), 'module' => $module, 'type' => AuthGroupModel::TYPE_ADMIN))
            ->getfield('id,id,title,rules');
        $node_list = $this->returnNodes($module);
        $map = array('module' => $module, 'type' => AuthRuleModel::RULE_MAIN, 'status' => 1);
        $main_rules = M('AuthRule')->where($map)->getField('name,id');
        $map = array('module' => $module, 'type' => AuthRuleModel::RULE_URL, 'status' => 1);
        $child_rules = M('AuthRule')->where($map)->getField('name,id');

        $this->assign('main_rules', $main_rules);
        $this->assign('auth_rules', $child_rules);
        $this->assign('node_list', $node_list);
        $this->assign('auth_group', $auth_group);
        $this->assign('this_group', $auth_group[$id]);
        $this->meta_title = '访问授权';
        $this->display('user_rule');
    }

    /*
     * 根据用户组ID获取用户组的模块
     */
    private function getModuleByGroupID($id){
        $where['id'] = $id;
        return M('AuthGroup')->where($where)->getfield('module');
    }
    public function updateRules($module){
        //需要新增的节点必然位于$nodes
        $nodes    = $this->returnNodes($module,false);
        $AuthRule = M('AuthRule');
        $map      = array('module'=>$module,'type'=>array('in','1,2'));//status全部取出,以进行更新
        //需要更新和删除的节点必然位于$rules
        $rules    = $AuthRule->where($map)->order('name')->select();
        //构建insert数据
        $data     = array();//保存需要插入和更新的新节点
        foreach ($nodes as $value){
            $temp['name']   = $value['url'];
            $temp['title']  = $value['title'];
            $temp['module'] = $module;
            if($value['pid'] >0){
                $temp['type'] = AuthRuleModel::RULE_URL;
            }else{
                $temp['type'] = AuthRuleModel::RULE_MAIN;
            }
            $temp['status']   = 1;
            $data[strtolower($temp['name'].$temp['module'].$temp['type'])] = $temp;//去除重复项
        }

        $update = array();//保存需要更新的节点
        $ids    = array();//保存需要删除的节点的id
        foreach ($rules as $index=>$rule){
            $key = strtolower($rule['name'].$rule['module'].$rule['type']);
            if ( isset($data[$key]) ) {//如果数据库中的规则与配置的节点匹配,说明是需要更新的节点
                $data[$key]['id'] = $rule['id'];//为需要更新的节点补充id值
                $update[] = $data[$key];
                unset($data[$key]);
                unset($rules[$index]);
                unset($rule['condition']);
                $diff[$rule['id']]=$rule;
            }elseif($rule['status']==1){
                $ids[] = $rule['id'];
            }
        }
        if ( count($update) ) {
            foreach ($update as $k=>$row){
                if ( $row!=$diff[$row['id']] ) {
                    $AuthRule->where(array('id'=>$row['id']))->save($row);
                }
            }
        }
        if ( count($ids) ) {
            $AuthRule->where( array( 'id'=>array('IN',implode(',',$ids)) ) )->save(array('status'=>-1));
            //删除规则是否需要从每个用户组的访问授权表中移除该规则?
        }
        if( count($data) ){
            $AuthRule->addAll(array_values($data));
        }
        if ( $AuthRule->getDbError() ) {
            trace('['.__METHOD__.']:'.$AuthRule->getDbError());
            return false;
        }else{
            return true;
        }
    }

    final protected function returnNodes($module, $tree = true)
    {
        static $tree_nodes = array();
        if ($tree && !empty($tree_nodes[(int)$tree])) {
            return $tree_nodes[$tree];
        }
        $where['module'] = $module;
        if ((int)$tree) {
            $list = M('Menu')->where($where)->field('id,pid,title,url,tip,hide')->order('sort asc')->select();
            foreach ($list as $key => $value) {
                if (stripos($value['url'], $module) !== 0) {
                    $list[$key]['url'] = $module . '/' . $value['url'];
                }
            }
            $nodes = list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'operator', $root = 0);
            foreach ($nodes as $key => $value) {
                if (!empty($value['operator'])) {
                    $nodes[$key]['child'] = $value['operator'];
                    unset($nodes[$key]['operator']);
                }
            }
        } else {
            $nodes = M('Menu')->where($where)->field('title,url,tip,pid')->order('sort asc')->select();
            foreach ($nodes as $key => $value) {
                if (stripos($value['url'], $module) !== 0) {
                    $nodes[$key]['url'] = $module . '/' . $value['url'];
                }
            }
        }
        $tree_nodes[(int)$tree] = $nodes;
        return $nodes;
    }
    //添加用户组权限
    public function writeGroup(){
        if (isset($_POST['rules'])) {
            sort($_POST['rules']);
            $_POST['rules'] = implode(',', array_unique($_POST['rules']));
        }else{
            $_POST['rules']='';
        }
        $_POST['type']   =  AuthGroupModel::TYPE_ADMIN;
        $AuthGroup       =  D('AuthGroup');
        $data = $AuthGroup->create();
        if ( $data ) {
            if ( empty($data['id']) ) {
                $r = $AuthGroup->add();
                //添加用户组的学校权限
                D('SchoolList')->addgroupId($r);
            }else{
                $r = $AuthGroup->save();
            }
            if($r===false){
                $this->error('操作失败'.$AuthGroup->getError());
            } else{
                $this->success('操作成功!',U('user_group'));
            }
        }else{
            $this->error('操作失败'.$AuthGroup->getError());
        }
    }

    /*
     * 审核机构
     */
    public function campus(){
		$departmentId = M('User')->where("id=".UID)->getField('department');
		
		$map['school_id'] = $departmentId;
		$list=M('school_area')->where($map)->order('id desc')->select();
		
        $this->assign('_list', $list);
		$this->display();    
    }
    public function sarea_add(){
		$departmentId = M('User')->where("id=".UID)->getField('department');
        if(I('name')){
            $data['name']     = I('name');
            $data['create_time']     = time();
            $data['school_id']     = $departmentId;
            $user            = M('school_area')->add($data);
			
			if($user){
				$result['result']   = 0;
				$result['msg']      = '添加成功';
            }else{
                $result['result']   = 1;
                $result['msg']      = '添加失败';
            }
            $this->ajaxReturn($result);
        }   
    }
	
    public function sarea_edit(){
		$departmentId = M('User')->where("id=".UID)->getField('department');
        if(I('name')){
            $data['id']     = I('id');
            $data['name']     = I('name');
            $data['create_time']     = time();
            $data['school_id']     = $departmentId;
            $user            = M('school_area')->save($data);

			if($user){
				$result['result']   = 0;
				$result['msg']      = '保存成功';
            }else{
                $result['result']   = 1;
                $result['msg']      = '保存失败';
            }
            $this->ajaxReturn($result);
        }   
    }	
    public function sarea_del(){
        if(I('id')){
            $data['id']     = I('id');
            $user            = M('school_area')->where(['id'=>$data['id']])->delete();

			if($user){
				$result['result']   = 0;
				$result['msg']      = '删除成功';
            }else{
                $result['result']   = 1;
                $result['msg']      = '删除失败';
            }
            $this->ajaxReturn($result);
        }   
    }

}
